<template>
  <div class="history-container">
    <!-- 顶部筛选栏 -->
    <div class="filter-bar">
      <div class="filter-tabs">
        <div class="tabs-left">
          <div
            v-for="tab in tabs"
            :key="tab.value"
            class="tab-item"
            :class="{ active: activeTab === tab.value }"
            @click="activeTab = tab.value"
          >
            {{ tab.label }}
          </div>
        </div>
        <div class="tabs-right">
          <div class="more-filter">更多筛选</div>
          <div
            class="batch-action"
            @click="toggleBatchMode"
          >
            {{ batchMode ? '取消' : '批量管理' }}
          </div>
          <div
            class="clear-action"
            @click="showClearDialog"
          >
            清空历史
          </div>
        </div>
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div class="batch-bar" v-if="batchMode">
      <div class="batch-left">
        <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
        <span class="selected-count">已选 {{ selectedItems.length }} 条</span>
      </div>
      <div class="batch-right">
        <el-button type="text" @click="batchDelete">删除</el-button>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧时间线导航 -->
      <div class="timeline-nav">
        <div
          v-for="(group, index) in filteredTimeGroups"
          :key="index"
          class="timeline-item"
          :class="{ active: activeTimeGroup === group.time }"
          @click="handleTimeGroupClick(group.time)"
        >
          <div class="timeline-dot"></div>
          <div class="timeline-label">{{ group.time }}</div>
          <div class="timeline-count">{{ group.count }}条</div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-area">
        <!-- 时间分组 -->
        <div
          class="time-group"
          v-for="(group, index) in filteredHistory"
          :key="index"
          v-show="activeTimeGroup === '全部' || group.time === activeTimeGroup"
        >
          <div class="time-label">{{ group.time }}</div>

          <!-- 历史记录项目 -->
          <div
            class="history-item"
            v-for="item in group.items"
            :key="item.id"
            :class="{ 'selected': isSelected(item.id) }"
          >
            <div class="item-left">
              <el-checkbox
                v-model="selectedItems"
                :label="item.id"
                v-if="batchMode"
                class="item-checkbox"
                @change="handleItemSelect"
              ></el-checkbox>
              <div class="item-type" v-if="item.tag">{{ item.tag }}</div>
              <el-image class="item-cover" :src="item.cover" fit="cover">
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="item-info">
                <div class="item-title">{{ item.title }}</div>
                <div class="item-desc">{{ item.desc }}</div>
                <div class="item-meta">
                  <span class="item-author">{{ item.author }}</span>
                  <span class="item-time">{{ item.displayTime }}</span>
                </div>
                <div class="item-progress" v-if="item.progress">
                  <el-progress
                    :percentage="item.progress.percent"
                    :show-text="false"
                    :stroke-width="4"
                  />
                  <span class="progress-text">{{ item.progress.text }}</span>
                </div>
              </div>
            </div>
            <div class="item-actions">
              <el-button
                type="text"
                :icon="Delete"
                circle
                @click="handleDelete(item.id)"
                v-if="!batchMode"
              />
              <el-button type="text" :icon="MoreFilled" circle v-if="!batchMode" />
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-if="filteredHistory.length === 0">
          <el-empty description="暂无历史记录" />
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
      center
    >
      <span>确定要删除这条历史记录吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>

    <!-- 清空历史对话框 -->
    <el-dialog
      v-model="clearDialogVisible"
      title="清空历史记录"
      width="400px"
      center
    >
      <span>确定要清空所有历史记录吗？此操作不可恢复</span>
      <template #footer>
        <el-button @click="clearDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmClear">确定清空</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Delete, MoreFilled, Picture } from '@element-plus/icons-vue'

// 状态管理
const tabs = ref([
  { label: '综合', value: 'all' },
  { label: '视频', value: 'video' },
  { label: '直播', value: 'live' },
  { label: '专栏', value: 'article' }
])
const activeTab = ref('all')
const searchQuery = ref('')
const activeTimeGroup = ref('全部')
const deleteDialogVisible = ref(false)
const clearDialogVisible = ref(false)
const itemToDelete = ref(null)
const batchMode = ref(false)
const selectedItems = ref([])
const selectAll = ref(false)

// 模拟数据
const historyData = ref([
  {
    id: 1,
    time: '昨天',
    type: 'video',
    tag: '原号',
    cover: 'https://dummyimage.com/160x90/ff6b6b/ffffff',
    title: 'JavaScript + Express 开发博客系统',
    desc: '超级干货 全栈项目',
    author: '千锋教育',
    displayTime: '14:57',
    progress: {
      percent: 94,
      text: '1534/1626'
    }
  },
  {
    id: 2,
    time: '昨天',
    type: 'video',
    tag: '新金榜',
    cover: 'https://dummyimage.com/160x90/74b9ff/ffffff',
    title: '前端学习路线',
    desc: '避坑攻略 自学必备',
    author: '千锋教育',
    displayTime: '14:39',
    progress: {
      percent: 0.4,
      text: '00:01/04:41'
    }
  },
  {
    id: 3,
    time: '昨天',
    type: 'video',
    cover: 'https://dummyimage.com/160x90/55efc4/ffffff',
    title: '大前端技术栈',
    desc: '全栈开发学习路线图',
    author: '国网讲全栈',
    displayTime: '14:38',
    progress: {
      percent: 0.1,
      text: '00:01/16:47'
    }
  },
  {
    id: 4,
    time: '昨天',
    type: 'video',
    cover: 'https://dummyimage.com/160x90/fdcb6e/ffffff',
    title: '高考失利 爆改人生？哪有这么容易',
    desc: '高考失利真的没关系吗？我也不想睁眼说瞎话...',
    author: '不加面的氨基酸',
    displayTime: '14:31',
    progress: {
      percent: 16,
      text: '00:02/12:06'
    }
  },
  {
    id: 5,
    time: '近一周',
    type: 'video',
    cover: 'https://dummyimage.com/160x90/a29bfe/ffffff',
    title: '只用137分钟 学会Nodejs',
    desc: '快速入门 NodeJS',
    author: '',
    displayTime: '周一',
    progress: {
      percent: 8,
      text: '00:03/05:25'
    }
  },
  {
    id: 6,
    time: '近一周',
    type: 'video',
    cover: 'https://dummyimage.com/160x90/ffeaa7/ffffff',
    title: '搭建Web服务器',
    desc: 'node',
    author: '',
    displayTime: '周二'
  }
])

// 计算属性
const filteredTimeGroups = computed(() => {
  const groups = [
    { time: '全部', count: filteredHistory.value.reduce((sum, group) => sum + group.items.length, 0) }
  ]

  filteredHistory.value.forEach(group => {
    groups.push({
      time: group.time,
      count: group.items.length
    })
  })

  return groups
})

const filteredHistory = computed(() => {
  // 按时间分组
  const timeGroups = {}
  historyData.value.forEach(item => {
    if (!timeGroups[item.time]) {
      timeGroups[item.time] = []
    }
    timeGroups[item.time].push(item)
  })

  // 转换为数组并过滤
  return Object.keys(timeGroups)
    .map(time => ({
      time,
      items: timeGroups[time].filter(item => {
        // 按标签过滤
        const typeMatch = activeTab.value === 'all' || item.type === activeTab.value
        // 按搜索词过滤
        const searchMatch = !searchQuery.value ||
          item.title.includes(searchQuery.value) ||
          item.desc.includes(searchQuery.value) ||
          (item.author && item.author.includes(searchQuery.value))

        return typeMatch && searchMatch
      })
    }))
    .filter(group => group.items.length > 0) // 只保留有内容的组
    .sort((a, b) => {
      // 排序：昨天 > 近一周 > 更早
      const order = { '昨天': 1, '近一周': 2 }
      return (order[a.time] || 3) - (order[b.time] || 3)
    })
})

// 方法
const handleTimeGroupClick = (time) => {
  activeTimeGroup.value = time
}

const handleDelete = (id) => {
  itemToDelete.value = id
  deleteDialogVisible.value = true
}

const confirmDelete = () => {
  historyData.value = historyData.value.filter(item => item.id !== itemToDelete.value)
  deleteDialogVisible.value = false
  itemToDelete.value = null
}

const showClearDialog = () => {
  clearDialogVisible.value = true
}

const confirmClear = () => {
  historyData.value = []
  clearDialogVisible.value = false
}

const toggleBatchMode = () => {
  batchMode.value = !batchMode.value
  if (!batchMode.value) {
    selectedItems.value = []
    selectAll.value = false
  }
}

const handleSelectAll = (val) => {
  if (val) {
    selectedItems.value = filteredHistory.value
      .flatMap(group => group.items)
      .map(item => item.id)
  } else {
    selectedItems.value = []
  }
}

const handleItemSelect = () => {
  const allItems = filteredHistory.value.flatMap(group => group.items)
  selectAll.value = selectedItems.value.length === allItems.length
}

const isSelected = (id) => {
  return selectedItems.value.includes(id)
}

const batchDelete = () => {
  if (selectedItems.value.length === 0) return

  historyData.value = historyData.value.filter(
    item => !selectedItems.value.includes(item.id)
  )
  selectedItems.value = []
  selectAll.value = false
}

// 初始化
onMounted(() => {
  // 可以在这里添加数据加载逻辑
})
</script>

<style scoped lang="scss">
.history-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;

  .filter-bar {
    background-color: #fff;
    padding: 0 20px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .filter-tabs {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 56px;

      .tabs-left {
        display: flex;
        align-items: center;
        height: 100%;

        .tab-item {
          padding: 0 16px;
          height: 100%;
          display: flex;
          align-items: center;
          cursor: pointer;
          font-size: 14px;
          color: #666;
          position: relative;

          &:hover {
            color: #fb7299;
          }

          &.active {
            color: #fb7299;
            font-weight: 500;

            &::after {
              content: '';
              position: absolute;
              bottom: 0;
              left: 16px;
              right: 16px;
              height: 2px;
              background-color: #fb7299;
            }
          }
        }
      }

      .tabs-right {
        display: flex;
        align-items: center;
        color: #666;
        font-size: 14px;

        .more-filter {
          padding: 0 12px;
          cursor: pointer;
        }

        .batch-action,
        .clear-action {
          padding: 0 12px;
          cursor: pointer;
          color: #666;

          &:hover {
            color: #fb7299;
          }
        }

        .clear-action {
          color: #999;
        }
      }
    }
  }

  .batch-bar {
    background-color: #fff;
    padding: 12px 20px;
    border-radius: 8px;
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .batch-left {
      display: flex;
      align-items: center;

      :deep(.el-checkbox) {
        margin-right: 16px;

        .el-checkbox__label {
          font-size: 14px;
        }
      }

      .selected-count {
        font-size: 14px;
        color: #666;
      }
    }

    .batch-right {
      .el-button {
        color: #666;
        font-size: 14px;

        &:hover {
          color: #fb7299;
        }
      }
    }
  }

  .main-content {
    display: flex;
    gap: 16px;

    .timeline-nav {
      width: 180px;
      background-color: #fff;
      border-radius: 8px;
      padding: 16px 0;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      height: fit-content;

      .timeline-item {
        padding: 12px 20px;
        cursor: pointer;
        display: flex;
        align-items: center;
        position: relative;
        transition: all 0.2s;

        &:hover {
          background-color: #f9f9f9;
        }

        &.active {
          background-color: #f0f7ff;

          .timeline-dot {
            background-color: #fb7299;
          }

          .timeline-label {
            color: #fb7299;
            font-weight: 500;
          }
        }

        .timeline-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #ddd;
          margin-right: 12px;
          flex-shrink: 0;
        }

        .timeline-label {
          font-size: 14px;
          color: #333;
          flex: 1;
        }

        .timeline-count {
          font-size: 12px;
          color: #999;
        }

        &::after {
          content: '';
          position: absolute;
          left: 27px;
          top: 28px;
          bottom: -28px;
          width: 2px;
          background-color: #eee;
          z-index: 1;
        }

        &:last-child::after {
          display: none;
        }
      }
    }

    .content-area {
      flex: 1;

      .time-group {
        background-color: #fff;
        border-radius: 8px;
        margin-bottom: 16px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        overflow: hidden;

        .time-label {
          padding: 12px 20px;
          font-size: 14px;
          color: #666;
          border-bottom: 1px solid #f0f0f0;
          background-color: #fafafa;
        }

        .history-item {
          display: flex;
          justify-content: space-between;
          padding: 16px 20px;
          border-bottom: 1px solid #f0f0f0;
          transition: all 0.2s;
          position: relative;

          &:hover {
            background-color: #f9f9f9;
          }

          &.selected {
            background-color: #f0f7ff;
          }

          .item-left {
            display: flex;
            flex: 1;
            overflow: hidden;

            .item-checkbox {
              margin-right: 12px;
              align-self: center;
            }

            .item-type {
              position: absolute;
              top: 16px;
              left: 20px;
              background-color: #fb7299;
              color: #fff;
              font-size: 12px;
              padding: 2px 6px;
              border-radius: 2px;
              z-index: 2;
            }

            .item-cover {
              width: 160px;
              height: 90px;
              border-radius: 4px;
              margin-right: 16px;
              flex-shrink: 0;
              background-color: #f5f5f5;

              .image-error {
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #f5f5f5;
                color: #999;
              }
            }

            .item-info {
              flex: 1;
              min-width: 0;

              .item-title {
                font-size: 16px;
                color: #333;
                font-weight: 500;
                margin-bottom: 6px;
                display: -webkit-box;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                overflow: hidden;
              }

              .item-desc {
                font-size: 14px;
                color: #666;
                margin-bottom: 6px;
                display: -webkit-box;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                overflow: hidden;
              }

              .item-meta {
                font-size: 12px;
                color: #999;
                margin-bottom: 8px;

                .item-author {
                  margin-right: 12px;
                }
              }

              .item-progress {
                display: flex;
                align-items: center;
                width: 100%;
                max-width: 400px;

                :deep(.el-progress) {
                  flex: 1;
                  margin-right: 10px;

                  .el-progress-bar {
                    padding-right: 0;
                    margin-right: 0;
                  }
                }

                .progress-text {
                  font-size: 12px;
                  color: #999;
                  flex-shrink: 0;
                }
              }
            }
          }

          .item-actions {
            display: flex;
            align-items: center;
            margin-left: 16px;

            .el-button {
              color: #999;
              padding: 6px;

              &:hover {
                color: #666;
                background-color: #f0f0f0;
              }
            }
          }
        }
      }

      .empty-state {
        background-color: #fff;
        border-radius: 8px;
        padding: 40px 0;
        text-align: center;
      }
    }
  }
}

:deep(.el-dialog__header) {
  margin-right: 0;
}

:deep(.el-dialog__body) {
  padding: 20px 25px;
  color: #666;
  text-align: center;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  text-align: center;
}
</style>
